package edu.uba.fcen.estimacion.word.selection.tales;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.log4j.Logger;

import edu.uba.fcen.estimacion.word.selection.WriterResult;
import edu.uba.fcen.estimacion.word.selection.constants.Constants;
import edu.uba.fcen.estimacion.word.selection.filter.FilterWords;
import edu.uba.fcen.estimacion.word.selection.filter.FilterWordsFactory;

public class GenerateOneFileWithAllTales {

	static Logger logger = Logger.getLogger(GenerateOneFileWithAllTales.class);
	
	public static void main(String[] args) {
		File directory = new File(Constants.TALES_FILES);
		WriterResult writer = new WriterResult(Constants.NAME_ALL_TALES_FILE, Constants.PATH_TALES);
		int amountOfFiles = directory.listFiles().length;
		logger.debug("There are " + amountOfFiles + " files.");
		Collection<String> filesWithError = new ArrayList<String>();
		for(File in : directory.listFiles()) {
			String name = in.getName();
			if (name.startsWith("cuento") && name.endsWith(".txt")) {
				try {
					FilterWords filter = FilterWordsFactory.getTalesFilter(in.getAbsolutePath());
					String line;
					while ((line = filter.readLine())!=null){
						writer.writeWithEnter(line);
					}
					logger.debug("Count down " + amountOfFiles);
					amountOfFiles--;
				} catch (NullPointerException e) {
					logger.error("There was a file with error " + name);
					filesWithError.add(name);
				}
			}
		}
		writer.close();
		printFilesWithErrors(filesWithError);
	}

	private static void printFilesWithErrors(Collection<String> filesWithError) {
		WriterResult writer = new WriterResult("ErrorFiles.txt", Constants.PATH_TALES);
		for (String name : filesWithError) {
			writer.writeWithEnter(name);
		}
		writer.close();
	}
	
}
